package com.webxp.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.webxp.DB.DBPoolMgr;

/**
 * 数据库 SQL执行类
 * 
 * @author hdg1988
 * 
 */
public class Filter {
	/**
	 * 日志记录
	 */
	private static org.apache.log4j.Logger logger = org.apache.log4j.Logger
			.getLogger("Filter.java");

	/**
	 * sql变量
	 */
	private static String sql = null;

	/**
	 * 构造函数
	 * 
	 * @param _sSelect
	 * @param _sFrom
	 */
	public Filter(String _sSelect, String _sFrom) {
		new Filter(_sSelect, _sFrom, "", "");
	}

	/**
	 * 构造函数，构造sql语句
	 * 
	 * @param _sSelect
	 * @param _sFrom
	 * @param _sWhere
	 * @param _sOrder
	 */
	public Filter(String _sSelect, String _sFrom, String _sWhere, String _sOrder) {
		StringBuffer _sql = new StringBuffer();
		_sql.append("select ").append(_sSelect).append(" from ").append(_sFrom);
		if (_sWhere.length() != 0)
			_sql.append(" where ").append(_sWhere);
		if (_sOrder.length() != 0) {
			_sql.append(" orderby ").append(_sOrder);
		}
		sql = _sql.toString();
	}

	/**
	 * sql执行语句
	 * 
	 * @return
	 */
	public ResultSet excureSQL() {
		// 获取数据库连接
		Connection con = null;
		try {
			con = DBPoolMgr.getDBPool().getConnection();
		} catch (Exception ex) {
			logger.info("获取数据库连接失败！");
			ex.printStackTrace();
			return null;
		}
		// 如果数据库连接为空
		if (con == null) {
			logger.info("获取数据库连接失败！");
			return null;
		}
		Statement state = null;
		if (sql != null) {
			try {
				state = con.createStatement();
				state.execute(sql);
				return state.getResultSet();
			} catch (Exception ex) {
				logger.info("执行数据库语句失败！ sql=" + sql);
				ex.printStackTrace();
				return null;
			}
		}
		return null;
	}

	public String toString() {
		return sql;
	}
}
